package main

import "math"

func test1() (int, int) {
	return 1, 2
}

func add(x, y int) int {
	return x + y
}

// 隐式返回
func add1(x, y int) (z int) {
	z = x + y
	return
}

func add2(x, y int) (z int) {
	{
		var z = x + y
		return z
	}
}

func add3(x, y int) (z int) {
	defer func() {
		z += 100
	}()
	z = x + y
	return
}

func add4(x, y int) (z int) {
	defer func() {
		println("add4", z) // 103
	}()
	z = x + y
	return z + 100
}
func sum(n ...int) int {
	var x int
	for _, v := range n {
		x += v
	}
	return x
}
func main() {
	x, _ := test1()
	println(x)            // 1
	println(add(test1())) // 3
	println(sum(1, 2, 3, 4, 5))
	println(add1(1, 2))
	println(add3(1, 2))
	println(add4(1, 2))

	// 匿名函数
	getSqrt := func(a float64) float64 {
		return math.Sqrt(a)
	}
	println(getSqrt(4))

	println("----匿名函数------")
	// --- function variable ---
	fn := func() {
		println("hello")
	}
	fn()
	// --- function collection ---
	fns := []func(x int) int{
		func(x int) int { return x + 1 },
		func(x int) int { return x + 2 },
	}
	println(fns[0](100))

	// --- function as field ---
	d := struct {
		fn func() string
	}{
		fn: func() string { return "Hello1, World!" },
	}
	println(d.fn())

	// --- channel of function ---
	fc := make(chan func() string, 2)
	fc <- func() string { return "Hello, World!" }
	println((<-fc)())

}
